const express = require('express')
const router = express.Router()
const RewardService = require('../services/rewardService')
const auth = require('../middleware/auth')
const { body, query, validationResult } = require('express-validator')
const logger = require('../utils/logger')

/**
 * 广告观看奖励
 * POST /api/v1/rewards/ad-watch
 */
router.post('/ad-watch', [
  auth,
  body('adId').isLength({ min: 1 }).withMessage('广告ID不能为空'),
  body('adType').isIn(['video', 'banner', 'interstitial', 'native']).withMessage('广告类型无效'),
  body('adSource').isLength({ min: 1 }).withMessage('广告来源不能为空'),
  body('platform').isIn(['miniprogram', 'h5']).withMessage('平台参数无效'),
  body('viewDuration').isInt({ min: 0 }).withMessage('观看时长必须是非负整数'),
  body('isCompleted').isBoolean().withMessage('完成状态必须是布尔值')
], async (req, res) => {
  try {
    // 验证参数
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '参数验证失败',
        errors: errors.array()
      })
    }

    const userId = req.user.id
    const { adId, adType, adSource, platform, viewDuration, isCompleted } = req.body
    const ipAddress = req.ip || req.connection.remoteAddress
    const userAgent = req.get('User-Agent')

    const result = await RewardService.rewardAdWatch(
      userId,
      adId,
      adType,
      adSource,
      platform,
      viewDuration,
      isCompleted,
      ipAddress,
      userAgent
    )

    res.json({
      success: true,
      code: 200,
      message: '广告观看记录成功',
      data: {
        rewardPoints: result.rewardPoints,
        todayViews: result.todayViews,
        remainingViews: result.remainingViews
      }
    })
  } catch (error) {
    logger.error('广告观看奖励失败:', error)
    
    let code = 500
    let message = '广告观看奖励失败'
    
    if (error.message === '用户不存在') {
      code = 404
      message = '用户不存在'
    } else if (error.message === '今日观看次数已达上限') {
      code = 400
      message = '今日观看次数已达上限'
    }
    
    res.status(code).json({
      success: false,
      code: code,
      message: message
    })
  }
})

/**
 * 邀请好友注册奖励
 * POST /api/v1/rewards/invite-register
 */
router.post('/invite-register', [
  auth,
  body('inviteeId').isInt({ min: 1 }).withMessage('被邀请人ID必须是正整数'),
  body('inviteCode').isLength({ min: 1, max: 8 }).withMessage('邀请码长度必须在1-8字符之间')
], async (req, res) => {
  try {
    // 验证参数
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '参数验证失败',
        errors: errors.array()
      })
    }

    const inviterId = req.user.id
    const { inviteeId, inviteCode } = req.body

    const result = await RewardService.rewardInviteRegister(inviterId, inviteeId, inviteCode)

    res.json({
      success: true,
      code: 200,
      message: '邀请注册奖励发放成功',
      data: {
        inviterReward: result.inviterReward.points,
        inviteeReward: result.inviteeReward.points
      }
    })
  } catch (error) {
    logger.error('邀请注册奖励失败:', error)
    
    let code = 500
    let message = '邀请注册奖励失败'
    
    if (error.message === '邀请人不存在' || error.message === '被邀请人不存在') {
      code = 404
      message = error.message
    } else if (error.message === '该用户已被邀请') {
      code = 400
      message = '该用户已被邀请'
    }
    
    res.status(code).json({
      success: false,
      code: code,
      message: message
    })
  }
})

/**
 * 邀请好友消费奖励（系统调用）
 * POST /api/v1/rewards/invite-consume
 */
router.post('/invite-consume', [
  auth,
  body('inviteeId').isInt({ min: 1 }).withMessage('被邀请人ID必须是正整数'),
  body('consumeAmount').isFloat({ min: 0.01 }).withMessage('消费金额必须大于0'),
  body('orderId').isInt({ min: 1 }).withMessage('订单ID必须是正整数')
], async (req, res) => {
  try {
    // 验证参数
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '参数验证失败',
        errors: errors.array()
      })
    }

    const { inviteeId, consumeAmount, orderId } = req.body

    const result = await RewardService.rewardInviteConsume(inviteeId, consumeAmount, orderId)

    res.json({
      success: true,
      code: 200,
      message: result ? '邀请消费奖励发放成功' : '无邀请关系，未发放奖励',
      data: result ? {
        rewardPoints: result.rewardPoints
      } : null
    })
  } catch (error) {
    logger.error('邀请消费奖励失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '邀请消费奖励失败'
    })
  }
})

/**
 * 充值赠送积分（系统调用）
 * POST /api/v1/rewards/recharge-bonus
 */
router.post('/recharge-bonus', [
  auth,
  body('rechargeAmount').isFloat({ min: 0.01 }).withMessage('充值金额必须大于0'),
  body('rechargeId').isInt({ min: 1 }).withMessage('充值记录ID必须是正整数')
], async (req, res) => {
  try {
    // 验证参数
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '参数验证失败',
        errors: errors.array()
      })
    }

    const userId = req.user.id
    const { rechargeAmount, rechargeId } = req.body

    const result = await RewardService.rewardRechargeBonus(userId, rechargeAmount, rechargeId)

    res.json({
      success: true,
      code: 200,
      message: '充值赠送积分成功',
      data: {
        basePoints: result.basePoints,
        bonusPoints: result.bonusPoints,
        totalPoints: result.totalPoints,
        bonusRate: result.bonusRate
      }
    })
  } catch (error) {
    logger.error('充值赠送积分失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '充值赠送积分失败'
    })
  }
})

/**
 * 活动奖励积分
 * POST /api/v1/rewards/activity
 */
router.post('/activity', [
  auth,
  body('points').isFloat({ min: 0.01 }).withMessage('奖励积分必须大于0'),
  body('activityName').isLength({ min: 1, max: 100 }).withMessage('活动名称长度必须在1-100字符之间'),
  body('activityId').isInt({ min: 1 }).withMessage('活动ID必须是正整数'),
  body('expireTime').optional().isISO8601().withMessage('过期时间格式无效')
], async (req, res) => {
  try {
    // 验证参数
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '参数验证失败',
        errors: errors.array()
      })
    }

    const userId = req.user.id
    const { points, activityName, activityId, expireTime } = req.body

    const result = await RewardService.rewardActivity(
      userId,
      points,
      activityName,
      activityId,
      expireTime ? new Date(expireTime) : null
    )

    res.json({
      success: true,
      code: 200,
      message: '活动奖励发放成功',
      data: {
        points: result.points,
        activityName: result.activityName,
        expireTime: result.expireTime
      }
    })
  } catch (error) {
    logger.error('活动奖励积分失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '活动奖励积分失败'
    })
  }
})

/**
 * 获取今日广告观看情况
 * GET /api/v1/rewards/today-ad-views
 */
router.get('/today-ad-views', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const result = await RewardService.getTodayAdViews(userId)

    res.json({
      success: true,
      code: 200,
      message: '获取今日广告观看情况成功',
      data: result
    })
  } catch (error) {
    logger.error('获取今日广告观看情况失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取今日广告观看情况失败'
    })
  }
})

/**
 * 获取邀请统计
 * GET /api/v1/rewards/invite-statistics
 */
router.get('/invite-statistics', auth, async (req, res) => {
  try {
    const userId = req.user.id
    const result = await RewardService.getInviteStatistics(userId)

    res.json({
      success: true,
      code: 200,
      message: '获取邀请统计成功',
      data: result
    })
  } catch (error) {
    logger.error('获取邀请统计失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: '获取邀请统计失败'
    })
  }
})

module.exports = router